var timeUtils = require ('./timeUtils');
var logUtils = require ('./logUtils');
var fmtUtils = require ('./fmtUtils');
var ocrCharMap = require ('./ocrCharMap');
if (!requestScreenCapture ()) {
  toastLog ('请求截图权限失败');
  exit ();
}
function toArray (arrLike) {
  var array = [];
  for (var index = 0; index < arrLike.length; index++) {
    var item = arrLike[index];
    array.push (item);
  }
  return array;
}
module.exports = {
  ocrResults: null,
  resetOcrResults () {
    this.ocrResults = null;
  },
  updateOcrResults () {
    var startTime = Date.now ();
    var captureImg = captureScreen ();
    if (!captureImg) {
      toastLog ('截图失败');
    }
    var hasExec = timeUtils.hasExec (startTime);
    if (hasExec > 1) {
      logUtils.info (fmtUtils.msg ('截图耗费时间', hasExec, '秒'));
    }
    this.ocrResults = toArray (gmlkit.ocr (captureImg, 'zh').toArray (3));
    setTimeout (() => {
      captureImg.recycle ();
    });
  },
  getRegExp (content, start, end) {
    var regExpStr = content
      .split ('')
      .map (function (item) {
        var match = ocrCharMap[item];
        var piece = match
          ? '[' + match.concat (item).join ('') + ']+'
          : '[' + item + ']+';
        return piece + `\\s*`;
      })
      .join ('');
    if (start) {
      regExpStr = '^' + regExpStr;
    }
    if (end) {
      regExpStr = regExpStr + '$';
    }
    return new RegExp (regExpStr, 'gi');
  },
  existsText (content) {
    if (!this.ocrResults) {
      return false;
    }
    var regExp = this.getRegExp (content, false, false);
    var length = this.ocrResults.length;
    for (var index = 0; index < length; index++) {
      var ocrResult = this.ocrResults[index];
      var ocrText = ocrResult.text;
      if (regExp.test (ocrText)) {
        return ocrResult;
      }
    }
    return false;
  },
  existsTextStartsWith (content) {
    if (!this.ocrResults) {
      return false;
    }
    var regExp = this.getRegExp (content, true, false);
    var length = this.ocrResults.length;
    for (var index = 0; index < length; index++) {
      var ocrResult = this.ocrResults[index];
      var ocrText = ocrResult.text;
      if (regExp.test (ocrText)) {
        return ocrResult;
      }
    }
    return false;
  },
  existsTextEndsWith (content) {
    if (!this.ocrResults) {
      return false;
    }
    var regExp = this.getRegExp (content, false, true);
    var length = this.ocrResults.length;
    for (var index = 0; index < length; index++) {
      var ocrResult = this.ocrResults[index];
      var ocrText = ocrResult.text;
      if (regExp.test (ocrText.trim ())) {
        return ocrResult;
      }
    }
    return false;
  },
};
